import clutter
import ui
import filepicker
import encode
import threading
import gtk
import gobject
import zenlog
import mtp
import sys
import traceback

filename = None

def run():
    global filename
    gtk.gdk.threads_init()
    
    logger = zenlog.get_log('main')
    
    def device_present(copier, allow_later=False):
        while not copier.detect(None):
            response = ui.ask_retry_device(allow_later)
            if response == ui.RETRY_CANCEL:
                return False
            if allow_later and response == ui.RETRY_LATER:
                return True
            
        return True
    
    def run_encoder():
        try:
            global filename
            observer = None
            encoder = encode.Encoder()
            
            selector = filepicker.VideoSelector()
            copier = mtp.MTPFileCopier()
            
            if filename == None:
                file = selector.choose_file()[0]
            else:
                file = filename
                
            encoder.set_output_bitrate("400")
            encoder.set_output_dimensions("320", "240")
            encoder.set_input_filename(file)
            
            observer = ui.EncoderProgressMonitor()
            observer.show()
            
            observer.set_activity('Checking for Media Player')
            observer.set_indeterminate()
    
            if device_present(copier, True):
                        
                encoder.add_output_observer(observer)
                observer.set_activity('Encoding Video')
                encoder.encode()
                
                copier.add_observer(observer)
                observer.set_activity('Sending to Media Player')
                outputfile = file
                fidx = outputfile.rfind('/') + 1
                eidx = outputfile.rfind('.')
                destfilename = outputfile[fidx:eidx]
                
                if device_present(copier, False):
                    copier.copy(encoder.get_outputfile(), destfilename)
                else:
                    pass
            else:
                pass
                
        except Exception, (instance):
            traceback.print_exc()
            ui.show_error(instance)
        finally:
            if observer:
                observer.destroy()
                
            gtk.main_quit()
        
    if len(sys.argv) == 2:
        filename = sys.argv[1] 
        
    # bunk off the logical flow in to a separate thread so we can
    # write readable code for the flow without blocking the ui
    encode_thread = threading.Thread(target=run_encoder)
    
    def start_thread():
        encode_thread.start()
        
    gobject.idle_add(start_thread)
    
    gtk.gdk.threads_enter()
    logger.info('starting gtk thread')
    gtk.main()
    logger.info('gtk thread finished')
    gtk.gdk.threads_leave()

if __name__ == "__main__":
    run()
